//
//  MQStatusPictureView.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/21.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

private let UICollectionViewCellId : String = "UICollectionViewCellId"

private let MQStatusMaxPictureCol:Int = 3
private let itemMargin:CGFloat = 5
private let itemWH = CGFloat(Int((SCREENW - 2*MQStatusCellMargin - 2*itemMargin) / CGFloat(MQStatusMaxPictureCol)))


class MQStatusPictureView: UICollectionView , UICollectionViewDataSource{
    
    var picUrls:[MQStatusPictureInfo]?{
        didSet{
            let count = picUrls!.count
//            contentLabel.text = "\(count)"
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(calcViewSize(count))
            }
            reloadData()
        }
    }
   override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
    
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    
    private func setupUI(){
        
        self.dataSource = self
        
        registerClass(MQStatusPictureViewCell.self, forCellWithReuseIdentifier: UICollectionViewCellId)
        
       let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(itemWH, itemWH)
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        
//        backgroundColor = RandomColor()
        
//        addSubview(contentLabel)
        
//        contentLabel.snp_makeConstraints { (make) -> Void in
//            make.center.equalTo(self)
//        }
    }
    
    private lazy var contentLabel:UILabel = {
        let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 35)
        return label
    }()
}

extension MQStatusPictureView{
    private func calcViewSize(count:Int) -> CGSize{
        
        if count == 1 {
            let key = picUrls?.first?.thumbnail_pic
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            if image != nil{
            
                var imageSize = image.size
                
                if imageSize.width < 80{
                    let width:CGFloat = 80
                    var height:CGFloat = width / imageSize.width * imageSize.height
                    if height > 150{
                        height = 150
                    }
                    
                    imageSize.width = width
                    imageSize.height = height
                }else if imageSize.width > 200 {
                    let width:CGFloat = 200
                    let height:CGFloat = width / imageSize.width * imageSize.height
                    
                    imageSize.width = width
                    imageSize.height = height
                }
                
                let layout = collectionViewLayout as! UICollectionViewFlowLayout
                layout.itemSize = imageSize
                return imageSize
            }else{
                return  CGSizeMake(itemWH, itemWH)
            }
            
        }else{
            let layout = collectionViewLayout as! UICollectionViewFlowLayout
            layout.itemSize = CGSizeMake(itemWH, itemWH)
        }
        
        let col = count == 4 ? 2 : (count > MQStatusMaxPictureCol ? MQStatusMaxPictureCol : count)
        let row = (count - 1) / col + 1
        
        let width = CGFloat(col)*itemWH + CGFloat(col - 1)*itemMargin
        let height = CGFloat(row)*itemWH + CGFloat(row - 1)*itemMargin
        
        return CGSizeMake(width, height)
    }
}
// MARK: - UICollectionViewDataSource
extension MQStatusPictureView{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(UICollectionViewCellId, forIndexPath: indexPath) as! MQStatusPictureViewCell
//        cell.backgroundColor = RandomColor()
        cell.picUrl = picUrls![indexPath.row]
        return cell
    }
}

// MARK: - 自定义cell
class MQStatusPictureViewCell:UICollectionViewCell{
    
    var picUrl:MQStatusPictureInfo?{
        didSet{
            if let url = picUrl?.thumbnail_pic{
                gifImageView.hidden = !url.hasSuffix(".gif")
                imageView.sd_setImageWithURL(NSURL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(contentView)
            make.bottom.equalTo(contentView)
        }
        
    }
    private lazy var imageView:UIImageView={
        
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
//        imageView.backgroundColor = RandomColor()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        imageView.sizeToFit()
        return imageView
    }()
    
    private lazy var gifImageView:UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "timeline_image_gif")
        return imageView
    }()
}